package com.okwanshiwu.payment.wxUtil;

import com.okwanshiwu.alarm.EmailAlarm;
import com.okwanshiwu.payment.common.AbstractPayType;
import com.okwanshiwu.payment.common.CommonPayUtil;
import com.okwanshiwu.util.TipCode;
import org.apache.log4j.Logger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

/**
 * 微信订单类
 * https://pay.weixin.qq.com/wiki/doc/api/index.html
 * @author
 * @create 2017-07-31 12:12
 **/
public class WxpayType extends AbstractPayType {

	private static Logger logger = Logger.getLogger(WxpayType.class);

	/**
	 * 统一下单
	 * @param orderId  订单号
	 * @param total_fee  单位是分，即是0.01元 * 100
	 * @param content 内容
	 * @return 标准格式信息
	 */
	@Override
	public String orderInfo(String orderId, int total_fee, String content,Map<String,String> other) {
		//实例化微信的相关参数
		WxProperties wxProperties = new WxProperties(content,orderId,total_fee,other.get("clientIp"),"APP",CommonPayUtil.getRandomString(16));
		//生成签名信息
		String sign = WxPayUtil.createSign(wxProperties);
		wxProperties.setSign(sign);
		//生成xml字符串信息
		String xmlInfo = WxPayUtil.wxPropertiesToXml(wxProperties);
		logger.debug(xmlInfo);
		String weixinPost = HttpXmlUtils.httpsRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", xmlInfo);
		Map<String,Object> orderRetInfo = ParseXMLUtils.jdomParseXml(weixinPost);
		if (orderRetInfo.get("return_code").equals("FAIL")){
			logger.error("与微信通信失败，无法生成预支付订单，时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			try {
				EmailAlarm.sendEmail("shaodafu@okwanshiwu.com","微信通信失败","");
			} catch (Exception e) {
				logger.error("邮件发送出现问题，请及时处理");
				e.printStackTrace();
			}
			return null;
		}
		if (orderRetInfo.get("result_code").equals("FAIL")){  //交易成功否（result_code在return_code为SUCCESS时才有）
			logger.error("交易失败，时间："+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
			try {
				EmailAlarm.sendEmail("shaodafu@okwanshiwu.com","微信通信失败","");
			} catch (Exception e) {
				logger.error("微信交易订单生成失败");
				e.printStackTrace();
			}
			return null;
		}
		int tmstr = (int) (System.currentTimeMillis()/100000);
		Map<String,String> sms = new TreeMap<String, String>();
		sms.put("appid",wxProperties.APPID);
		sms.put("noncestr",wxProperties.getNonce_str());
		sms.put("package","Sign=WXPay");
		sms.put("partnerid",wxProperties.MCH_ID);
		sms.put("prepayid",orderRetInfo.get("prepay_id")+"");
		sms.put("timestamp",tmstr+"");
		sms.put("sign", WxPayUtil.createSign(sms).toUpperCase());
		sms.put("transaction_id", wxProperties.getOut_trade_no());
		TipCode tip = new TipCode();
		tip.putData("data", sms);
		tip.setCodeAndMsg(10033, "获取微信预支付单成功");
		return tip.toJson();
	}

	/**
	 * 查询订单信息
	 * @param orderId  商户订单号
	 * @return
	 * 流程信息详见：https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_2&index=4
	 */
	@Override
	public boolean getOrderResult(String orderId) {
		return (WxPayUtil.orderResult(orderId)==null)?false:true;
	}

	/**
	 * 查询订单信息
	 * @param orderId  商户订单号
	 * @param  price 订单价格，单位分
	 * @return
	 * 流程信息详见：https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_2&index=4
	 */
	@Override
	public boolean getOrderResult(String orderId, int price) {
		WXQueryOrderResult wx = WxPayUtil.orderResult(orderId);
		int total_fee = wx.getTotal_fee();
		return total_fee==price ? true:false;
	}


	@Override
	public String refundOrder(String refundId, String orderId) {
		return null;
	}
}
